<?php
/**
 * Created by : PhpStorm
 * Message: 登录控制器
 * User: bingdi
 * Time: 2020/2/1813:08
 * motto: 现在的努力是为了小时候吹过的牛逼!
 */

namespace app\admin\controller;


use app\common\model\Role;
use think\App;
use think\Db;
use think\facade\View;
use think\captcha\facade\Captcha;
use think\Session;

class Login extends AdminBase
{

    public function initialize()
    {
        $action=$this->request->action();
        //是否登录已切换到中间件处理
        if ($this->isLogin()&&!in_array($action,['logout','cut_language'])) {
            return $this->redirect(url('index/index'));
        }
//        parent::initialize(); // TODO: Change the autogenerated stub
    }
    //切换语言
    public function cut_language(){
        $id=input('param.id');
        session('language',$id);
        if ($id==1){
            session('language_text','中文');
        }elseif ($id==2){
            session('language_text','日语');
        }
        return $this->redirect(url('index/index'));
    }
    public function index()
    {
        return View::fetch('login');
    }

    public function login()
    {
        if (request()->isPost()) {
            $data = input('post.');
//            return show(1,'登录成功',['url'=>'Index/index']);
            $admin = \think\facade\Db::name('admin')->where('name', $data['name'])
                ->find();
            if (!$admin || $admin['status'] != 1) {
                return show(0,'请登录真确身份的管理员账号');
            }
            if ($admin['password'] != md5($data['password'])) {
                return show(0,'密码输入错误');
            }
            //1.更新数据库 登陆时间 登录ip
            $udata = [
                //登录时间
                'login_time' => date("Y-m-d H:i:s",time()),
                //登录IP
                'login_ip' => request()->ip(),
            ];
            try {
                \think\facade\Db::name('admin')
                    ->where('id',$admin['id'])
                    ->update($udata);
            } catch (\Exception $e) {
                return show(0,$e->getMessage());
            }
            $admin = \think\facade\Db::name('admin')->where('name', $data['name'])
                ->field('id,name,role_id,login_time,login_ip')
                ->find();
            //2.session
//            $admin['role_name']=Role::getById()[$admin['role_id']];
            session('adminuser', $admin);
            return show(1,'登录成功',['url'=>'Index/index']);
        } else {
            return show(0, '请求不合法');
        }
    }

    public function md5()
    {
        halt(session(config('admin.session_admin')));
    }

    //退出登录的逻辑
    public function logout()
    {
        //清空session
        session(null);
//        session(null,config('admin.session_user_scope'));
        //跳转到登录页面
        $this->redirect('/admin');
    }

}